<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="模块标题">
            <el-input v-model="queryParams.title" placeholder="请输入模块标题" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="操作人员">
            <el-input v-model="queryParams.oper_name" placeholder="请输入操作人员" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select v-model="queryParams.business_type" placeholder="请选择操作类型" clearable>
              <el-option v-for="item in businessTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作状态">
            <el-select v-model="queryParams.status" placeholder="请选择操作状态" clearable>
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery">查询</el-button>
            <el-button :icon="RefreshRight" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="mb-2 flex justify-between">
        <div>
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
          <el-button type="danger" @click="handleClean">清空日志</el-button>
        </div>
        <div>
          <el-input v-model="searchValue" placeholder="请输入关键字搜索" style="width: 200px;" clearable @keyup.enter="handleSearch" />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="logList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="日志编号" width="80" align="center" />
        <el-table-column prop="title" label="模块标题" width="120" align="center" />
        <el-table-column prop="business_type" label="业务类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getBusinessTypeTag(scope.row.business_type)">
              {{ getBusinessTypeLabel(scope.row.business_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="method" label="请求方式" width="80" align="center" />
        <el-table-column prop="oper_name" label="操作人员" width="100" align="center" />
        <el-table-column prop="oper_ip" label="操作IP" width="120" align="center" />
        <el-table-column prop="oper_url" label="请求地址" width="160" align="center" />
        <el-table-column prop="oper_location" label="操作地点" width="120" align="center" />
        <el-table-column prop="status" label="操作状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
              {{ scope.row.status === 0 ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="oper_time" label="操作时间" width="160" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialog" title="操作日志详情" width="700px">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="操作模块">{{ detailForm.title }}</el-descriptions-item>
          <el-descriptions-item label="操作人员">{{ detailForm.oper_name }}</el-descriptions-item>
          <el-descriptions-item label="请求地址">{{ detailForm.oper_url }}</el-descriptions-item>
          <el-descriptions-item label="请求方式">{{ detailForm.method }}</el-descriptions-item>
          <el-descriptions-item label="操作IP">{{ detailForm.oper_ip }}</el-descriptions-item>
          <el-descriptions-item label="操作状态">
            <el-tag :type="detailForm.status === 0 ? 'success' : 'danger'">
              {{ detailForm.status === 0 ? '正常' : '异常' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作时间">{{ detailForm.oper_time }}</el-descriptions-item>
          <el-descriptions-item label="业务类型">
            <el-tag :type="getBusinessTypeTag(detailForm.business_type)">
              {{ getBusinessTypeLabel(detailForm.business_type) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">请求参数</el-divider>
        <el-input
          v-model="detailForm.oper_param"
          type="textarea"
          :rows="5"
          readonly
        />

        <el-divider content-position="left">返回结果</el-divider>
        <el-input
          v-model="detailForm.json_result"
          type="textarea"
          :rows="5"
          readonly
        />

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialog = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import requestUtil, {getServerUrl} from '@/util/request'
import { Search, Tools, RefreshRight, Edit, Delete,Plus } from '@element-plus/icons-vue'


// 状态选项
const statusOptions = [
  { value: 0, label: '正常' },
  { value: 1, label: '异常' }
]

// 业务类型选项
const businessTypeOptions = [
  { value: 0, label: '查询' },
  { value: 1, label: '新增' },
  { value: 2, label: '修改' },
  { value: 3, label: '删除' },
  { value: 4, label: '授权' },
  { value: 5, label: '导出' },
  { value: 6, label: '导入' },
  { value: 7, label: '强退' },
  { value: 8, label: '生成代码' },
  { value: 9, label: '清空数据' }
]

// 获取业务类型标签样式
const getBusinessTypeTag = (type) => {
  const map = {
    0: 'info', // 将空字符串改为 'info'
    1: 'success',
    2: 'warning',
    3: 'danger',
    4: 'info',
    5: 'primary',
    6: 'primary',
    7: 'danger',
    8: 'success',
    9: 'danger'
  }
  return map[type] || 'info' // 默认返回 'info' 而不是空字符串
}

// 获取业务类型标签文本
const getBusinessTypeLabel = (type) => {
  const option = businessTypeOptions.find(item => item.value === type)
  return option ? option.label : '未知'
}

// 数据加载状态
const loading = ref(false)
// 日志列表数据
const logList = ref([])
// 总记录数
const total = ref(0)
// 选中的记录ID
const selectedIds = ref([])
// 搜索关键字
const searchValue = ref('')
// 详情对话框显示状态
const detailDialog = ref(false)
// 详情表单数据
const detailForm = ref({})

// 查询参数
const queryParams = ref({
  page: 1,
  limit: 10,
  title: '',
  business_type: '',
  status: '',
  oper_name: '',
  ordering: '-oper_time' // 默认按操作时间降序
})

// 获取日志列表数据
const getList = async () => {
  loading.value = true
  try {
    if (searchValue.value) {
      queryParams.value.search = searchValue.value
    }
    const response = await requestUtil.get('/system/oper_log/', queryParams.value)
    logList.value = response.results || []
    total.value = response.count || 0
  } catch (error) {
    console.error('获取日志列表失败', error)
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮点击事件
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.title = ''
  queryParams.business_type = ''
  queryParams.status = ''
  queryParams.oper_name = ''
  searchValue.value = ''
  handleQuery()
}

// 搜索按钮点击事件
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 表格选择变化事件
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化事件
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

// 当前页变化事件
const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 查看详情
const handleDetail = (row) => {
  detailForm.value = { ...row }
  // 尝试格式化JSON字符串
  try {
    if (typeof detailForm.value.oper_param === 'string') {
      const paramObj = JSON.parse(detailForm.value.oper_param)
      detailForm.value.oper_param = JSON.stringify(paramObj, null, 2)
    }
    if (typeof detailForm.value.json_result === 'string') {
      const resultObj = JSON.parse(detailForm.value.json_result)
      detailForm.value.json_result = JSON.stringify(resultObj, null, 2)
    }
  } catch (e) {
    console.error('JSON格式化失败', e)
  }
  detailDialog.value = true
}

// 删除单条记录
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除编号为 ${row.id} 的日志记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await requestUtil.delete(`/system/oper_log/${row.id}/`)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条日志记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await requestUtil.post('/system/oper_log/batch_delete/', { ids: selectedIds.value })
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {})
}

// 清空日志
const handleClean = () => {
  ElMessageBox.confirm('确认清空所有操作日志记录吗？此操作不可逆！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await requestUtil.del('/system/oper_log/clean/')
      ElMessage.success('清空日志成功')
      getList()
    } catch (error) {
      console.error('清空日志失败', error)
      ElMessage.error('清空日志失败')
    }
  }).catch(() => {})
}

// 组件挂载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>